package infomap.smsSender

import infomap.Usuario

/**
 * User: mwaisgold
 * Date: 16/10/11
 * Time: 23:31
 */
class Gateway160SMSSender implements SMSSender {
    def sendMessage(Usuario receiver, msj) {
        HashMap params = new HashMap();
        params.put("accountName", "mwaisgold");
        params.put("key", "811a0f76-560f-4660-9970-7b0c62a8559b");
        params.put("phoneNumber", receiver.celular);
        params.put("message", msj);
        params.put("countryCode", "AR");

        try {

            URL url = new URL("http://api.gateway160.com/client/sendmessage/");
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setRequestMethod("POST");

            // write post body
            OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
            String postBody = encode(params);
            out.write(postBody);
            out.flush();
            out.close();


            // Get the response
            StringBuilder sb = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();


            System.out.println("responseCode=" + httpCon.getResponseCode());
            System.out.println("responseBody=" + sb.toString());


        } catch (IOException e) {
            System.out.println("IOException thrown: " + e.getMessage());
        }
    }

    String encode(final HashMap params) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder()

        params.each { k,v ->
            sb.append(URLEncoder.encode(k, "UTF-8"))
            sb.append("=")
            sb.append(URLEncoder.encode(v, "UTF-8"))
            sb.append("&")
        }

        sb.toString()
    }

}
